<template>
  <el-dialog title="books" v-model="dialogFormVisible">
    <el-form
      :model="form"
      enctype="multipart/form-data"
      ref="formRef"
      :rules="rules"
    >
      <el-form-item label="ISBN" prop="isbn" :label-width="formLabelWidth" class="isbn">
        <el-input v-model="form.isbn" autocomplete="off"></el-input>
        <span class="search" @click="search">search</span>
      </el-form-item>
      <el-form-item
        label="book name"
        prop="bookName"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.bookName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="category"
        prop="categoryId"
        :label-width="formLabelWidth"
      >
        <el-select
          v-model="form.categoryId"
          name="categoryId"
          placeholder="please select the active region"
        >
          <el-option
            v-for="category in categorys"
            :label="category.categoryName"
            :value="category.id"
            :key="category.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="author" prop="author" :label-width="formLabelWidth">
        <el-input v-model="form.author" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="publisher"
        prop="publisher"
        :label-width="formLabelWidth"
      >
        <el-input v-model="form.publisher" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="publishDate"
        prop="publishDate"
        :label-width="formLabelWidth"
      >
        <el-date-picker
          v-model="form.publishDate"
          type="date"
          placeholder="publishDate"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="unit Price" prop="unitPrice" :label-width="formLabelWidth">
        <el-input v-model="form.unitPrice" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="img" prop="imgUrl" :label-width="formLabelWidth">
        <el-input v-model="form.imgUrl" autocomplete="off"></el-input>
        <!-- <input type="file" @change="setImg($event)" /> -->
      </el-form-item>

      <el-form-item label="summary" prop="summary" :label-width="formLabelWidth">
        <el-input v-model="form.summary" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="count" prop="allNum" :label-width="formLabelWidth">
        <el-input v-model="form.allNum" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="rackNumber" prop="rackNumber" :label-width="formLabelWidth">
        <!-- <el-input v-model="form.rackNumber" autocomplete="off"></el-input> -->
        <el-select v-model="floor" placeholder="floor" width="50px">
          <el-option v-for="item in floorOp" :key="item" :value="item" />
        </el-select>
        <el-select v-model="face" placeholder="face">
          <el-option v-for="item in faceOp" :key="item" :value="item" />
        </el-select>
        <el-select v-model="row" placeholder="row">
          <el-option v-for="item in rowOp" :key="item" :value="item" />
        </el-select>
        <el-select v-model="col" placeholder="col">
          <el-option v-for="item in colOp" :key="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="tag" prop="tags" :label-width="formLabelWidth">
        <el-input v-model="form.tags" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">cancel</el-button>
        <el-button type="primary" @click="upload">confirm</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type { Category } from "@/domain/book";
import { ElMessage, type FormInstance } from "element-plus";
import { computed, InputHTMLAttributes, onMounted, ref, watch } from "vue";
import * as bookApi from "@/api/books";
import { searchByCrypto } from "@/api/searchByCrypto";
import { log } from "console";

const props = defineProps<{
  mode: 1 | 0;
  visible: boolean;
  isbn?: string;
}>();
const formLabelWidth = ref("120px");

const form = ref({
  isbn: "",
  categoryId: "",
  bookName: "",
  author: "",
  publisher: "",
  publishDate: "",
  rackNumber: "",
  unitPrice: "",
  imgUrl: "",
  summary: "",
  allNum: 0,
  tags: "",
});

const rules = {
  isbn: [{ required: true, message: "please enter the ISBN", trigger: "blur" }],
  categoryId: [{ required: true, message: "please enter the category", trigger: "blur" }],
  bookName: [{ required: true, message: "please enter the book name", trigger: "blur" }],
  author: [{ required: true, message: "please enter the author", trigger: "blur" }],
  publisher: [{ required: true, message: "please enter the publisher", trigger: "blur" }],
  publishDate: [{ required: true, message: "please enter the publishDate", trigger: "blur" }],
  rackNumber: [{ required: false, message: "please enter the rackNumber", trigger: "blur" }],
  unitPrice: [{ required: true, message: "please enter the unit price", trigger: "blur" }],
  imgUrl: [{ required: true, message: "please enter the imgUrl", trigger: "blur" }],
  summary: [{ required: true, message: "please enter the summary", trigger: "blur" }],
  allNum: [{ required: true, message: "please enter the count", trigger: "blur" }],
};

const getBookLocation = () => {
  bookApi.getBookLocation().then((data) => {
    const bookLocation = data[0];
    floorOp.value = Array.from({ length: bookLocation.floor}, (v, i) => i + 1);
    faceOp.value = Array.from({ length: bookLocation.face}, (v, i) => i + 1);
    rowOp.value = Array.from({ length: bookLocation.row0}, (v, i) => i + 1);
    colOp.value = Array.from({ length: bookLocation.col}, (v, i) => i + 1);
  });
}

const floorOp = ref([]);
const floor = ref();
const faceOp = ref([]);
const face = ref();
const rowOp = ref([]);
const row = ref();
const colOp = ref([]);
const col = ref();
const setRackNumber = () => {
  floor.value = Math.floor(form.value.rackNumber / 10000);
  face.value = Math.floor(form.value.rackNumber % 10000 / 100);
  row.value = Math.floor(form.value.rackNumber % 100 / 10);
  col.value = Math.floor(form.value.rackNumber % 10);
}

const setImg = (event: Event) => {
  form.value.imgUrl = (event?.target as HTMLInputElement)
    ?.files?.[0] as any as string; // get input file object
};

const mode = ref<0 | 1>(0);
const formRef = ref<FormInstance>();
const originIsbn = ref("");
const emit = defineEmits<{
  (event: "update:visible", val: boolean): void;
  (event: "upload"): void;
}>();
const dialogFormVisible = computed({
  get() {
    return props.visible;
  },
  set(val: boolean) {
    emit("update:visible", val);
  },
});
watch(
  () => props.visible,
  () => {
    if (!props.visible) {
      return;
    }
    if (props.mode === 0) {
      initEmptyDialog();
    } else {
      if (props.isbn) {
        initDialogData(props.isbn);
      }
    }
  }
);
const initEmptyDialog = () => {
  originIsbn.value = "";
  rules.imgUrl[0].required = true;
  (Object.keys(form.value) as Array<keyof typeof form.value>).forEach((key) => {
    if (key === "allNum") {
      form.value.allNum = 0;
    } else {
      form.value[key] = "";
    }
  });
  mode.value = 0;
};
const initDialogData = (isbn: string) => {
  rules.imgUrl[0].required = false;
  originIsbn.value = isbn;
  bookApi.getBook({ isbn: originIsbn.value }).then((data) => {
    Object.assign(form.value, data);
    setRackNumber();
  });
  mode.value = 1;
};

const search = async () => {
  const queryData = await searchByCrypto(form.value.isbn || -1);
  console.log('queryData', queryData);
  if (queryData?.ret_code === undefined || queryData?.ret_code === -1) {
    ElMessage.error("please enter the userId and password");
    return;
  }
  const { data = {} } = queryData;
  console.log('form', form, form.value);

  const book = {
    isbn: data.isbn,
    bookName: data.title,
    categoryId: 1,
    author: data.author,
    publisher: data.publisher,
    publishDate: data.pubdate,
    unitPrice: data.price,
    imgUrl: data.img,
    summary: data.gist,
    // rackNumber: '请手动输入',
    // allNum: '请手动输入',
  }
  Object.assign(form.value, book);
  console.log('form', form, form.value);
}

const upload = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      form.value.publishDate = new Date(
        form.value.publishDate
      ) as any as string;
      const formData = new FormData();
      formData.set("imgUrl", form.value.imgUrl);
      console.log('form.value', form.value);
      for (let key in form.value) {
        formData.set(
          key,
          form.value[key as keyof typeof form.value] as string
        );
      }

      let uploadMethod;
      if (mode.value === 0) {
        uploadMethod = bookApi.uploadBook;
      } else {
        uploadMethod = bookApi.updateBook;
        formData.set("originIsbn", originIsbn.value);
      }
      formData.set("rackNumber", floor.value * 10000 + face.value * 100 + row.value * 10 + col.value);
      console.log('formData', formData);
      for(var pair of formData.entries()) {
        console.log(pair[0]+ ', '+ pair[1]);
      }

      uploadMethod(formData, { "Content-Type": "multipart/form-data" })
      .then(
        () => {
          dialogFormVisible.value = false;
          ElMessage({
            message: mode.value === 0 ? "add success" : "modify success",
            type: "success",
          });
          emit("upload");
        }
      )
      .catch(err => {
        ElMessage.error(err);
      });
    }
  });
};

const categorys = ref<Category[]>([]);
const getCategory = () => {
  bookApi.getCategory().then((data) => {
    categorys.value = data;
  });
};
onMounted(() => {
  getCategory();
  getBookLocation();
});
</script>
<style scoped>
.isbn {
  position: relative;
}
.search {
  position: absolute;
  right: 10px;
}
.search:hover {
  color: #409eff;
  cursor: pointer;
}
</style>
